<template>
  <canvas
    ref="code"
    style="width: 100px; height: 36px"
    @click="getCode"
  ></canvas>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { userApi } from '@/api'
const code = ref()
const emit = defineEmits(['update:validateCode'])
async function getCode() {
  const { data } = await userApi.getGraphicsCode()
  handleCanvas(data)
  emit('update:validateCode', data)
}
function handleCanvas(data) {
  const codeCanvas = code.value
  codeCanvas.width = 100
  codeCanvas.height = 36
  const codeContext = codeCanvas.getContext('2d')
  drawCode(codeContext, data)
  setLine(codeContext)
  setDot(codeContext)
}
function drawCode(cxt, code) {
  for (let i = 0; i < code.length; i++) {
    const x = 15 + 20 * i
    const y = 10 + Math.random() * 25 //产生一个随机值
    const myChar = code.charAt(i)
    cxt.font = 'normal 16px 微软雅黑' //设置
    cxt.fillStyle = getColor() //设置字体颜色
    cxt.fillText(myChar, x, y)
  }
}
function setLine(cxt) {
  for (let i = 0; i < 8; i++) {
    cxt.beginPath()
    cxt.moveTo(Math.random() * 120, 40 * Math.random())
    cxt.lineTo(Math.random() * 120, 40 * Math.random())
    cxt.strokeStyle = getColor() //设置干扰线颜色
    cxt.stroke() //绘制执行
  }
}
function setDot(cxt) {
  for (let i = 0; i < 20; i++) {
    cxt.beginPath()
    const x = Math.random() * 120
    const y = Math.random() * 40
    cxt.moveTo(x, y)
    cxt.lineTo(x + 1, y + 1)
    cxt.strokeStyle = getColor() //设置干扰点颜色
    cxt.stroke() //绘制执行
  }
}
function getColor() {
  const r = Math.floor(Math.random() * 256)
  const g = Math.floor(Math.random() * 256)
  const b = Math.floor(Math.random() * 256)
  return 'rgb(' + r + ',' + g + ',' + b + ')'
}

onMounted(() => {
  getCode()
})
</script>
